<?php
/**
 * 建行异步通知
 * @author feyeen
 * date 2016-4-18
 */
namespace api\controllers;

class NotifyCcbController extends BaseCoreController
{
    public $path='';
    public $ORDER_PAYCCB_VERIFICATION = '验证失败';
    public $ORDER_PAYCCB_WAILL = '订单等待支付';
    public $ORDER_PAYCCB_OK = '订单支付成功';
    public $ORDER_PAYCCB_FAIL = '订单支付失败';
    public $ORDER_PAYCCB_LOOK_FAIL = '订单查询失败';
    public $TRADE_STATUS='F';

    //初始化
    public function init(){
        parent::init();
        $this->path =  Yii::$app->params['root_log'];
    }

    //异步通知
    public function actionIndex(){

        //初始化日志
        $logHandler= new CLogFileHandler($this->path."/ccb/".date('Y-m-d').'.log');
        Log::Init($logHandler, 15);

        //验证
        $query_string =  $_SERVER["QUERY_STRING"];
        //$query_string = "POSID=652468641&BRANCHID=310000000&ORDERID=90477&PAYMENT=0.01&CURCODE=01&REMARK1=&REMARK2=&SUCCESS=Y&TYPE=1&REFERER=&CLIENTIP=203.156.252.146&SIGN=7e167e410c3f0e84c656daf665826736cb6e2a5a6dd93b6a507c81463fce6d3a09abaf89e9cc28af4a1e76594dd87d41cf1841fc076365cacee1c5b598a5f7d5d28f8848e39badf6308290c2ae4d12b3ca03265968d0d1611653197ae8807c4eaba84f6738fbcda436df121754c311f387845da9d54c25e509409547a4bebec1\n";
        $variSocket = Ccbalipay::variSocket('127.0.0.1','55535',"{$query_string}\n");
        try{
            if($variSocket[0] =='Y'){
                $result = Yii::$app->request->get();
                $out_trade_no = trim($result['ORDERID']); // 商户订单号
                $total_fee = trim($result['PAYMENT']);    // 交易金额
                $this->TRADE_STATUS = trim($result['SUCCESS']); // 交易状态：成功－Y，失败－N
                Log::INFO($this->logStr($result));
                //查询订单信息
                if($out_trade_no && $this->TRADE_STATUS == 'Y' && $total_fee != 0){
                    $order_info = OrderInfo::find()->select(['bestry_uid','status','pay_status','order_amount','order_info_id','order_sn'])->where(['order_sn'=>$out_trade_no])->asArray()->one();

                    //找不到订单跳转404 并且记录日志
                    if(empty($order_info)) {
                        Log::DEBUG($this->logStr($out_trade_no.$this->ORDER_PAYCCB_LOOK_FAIL));
                        exit;
                        //return $this->redirect(UrlManager::createUrl('',''));
                    }

                    //订单支付成功修改订单状态为已支付：1，支付状态为成功：1 并且记录日志
                    if(!empty($order_info) &&  $order_info['status']== OrderInfo::$STATUS_ORDER_CREATED && $order_info['pay_status'] == OrderInfo::$PAY_STATUS_WAIT) {

                        //插入日志
                        Log::DEBUG($out_trade_no.$this->ORDER_PAYCCB_WAILL);

                        //支付成功更改状态支付状态的时候，插入一条order_log 插入一条 exp_info，失败只记录日志
                        if(Order::orderStatusChangePayed($order_info['order_info_id'])){

                            //更新paylog状态
                            if($this->payLogInfo($order_info) == false){

                                Log::DEBUG($out_trade_no.$this->ORDER_PAYCCB_FAIL);
                                exit;
                            }

                            //更新和跳转
                            Log::DEBUG($out_trade_no.$this->ORDER_PAYCCB_OK);
                            echo "success";
                        }else{

                            //记录日志和返回失败
                            Log::DEBUG($out_trade_no.$this->ORDER_PAYCCB_FAIL);
                            echo "fail";
                        }
                    }

                    Log::DEBUG($out_trade_no.$this->ORDER_PAYCCB_FAIL);
                    echo "fail";

                }else{
                    Log::INFO( $this->ORDER_PAYCCB_LOOK_FAIL);
                    echo "fail";
                }

            }else{
                //验证失败
                Log::ERROR($this->ORDER_PAYCCB_VERIFICATION);
                echo "fail";
            }
        }catch(Exception $e){
            Log::ERROR($e->getMessage());
            echo "fail";
        }
    }

    //组装订单信息日志
    private function logStr($params){
        $timeout = date('Y-m-d H:m:s',time());
        $str = $timeout.'------';
        if(is_array($params)){
            foreach($params as $key=>$val){
                $str .= $key.'=>'.$val;
            }
        }else
            $str = $str .'=>'. $params;
        return $str;
    }

    //更改建行支付状态
    private function payLogInfo($params){
        if(!is_array($params))
            return false;

        $payLogInfo = PayLog::findOne(['order_info_id'=>$params['order_info_id'],'order_sn'=>$params['order_sn']]);

        if($payLogInfo){

            //更改支付状态
            $payLogInfo->trade_status=$this->TRADE_STATUS;
            $payLogInfo->notify_time=date("Y-m-d H:i:s");
            $payLogInfo->save();
            return true;
        }else{
            Log::WARN($params['order_sn'].$this->ORDER_PAYCCB_LOOK_FAIL);
        }
        return false;

    }
}

?>